package com.gexiaobao.pigeon.ui.fragment.mine.organization

import android.net.Uri
import android.os.Bundle
import androidx.media3.common.MediaItem
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.databinding.FragmentLivingInteractionBinding
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.viewmodel.VideoViewModel
import me.hgj.jetpackmvvm.util.LogUtils

/**
 * @Author      : hxw
 * @Date        : 2024/11/18 17:57
 * @Describe    : 直播互动（直播）
 */
class FragmentLivingInteraction : BaseFragment<VideoViewModel, FragmentLivingInteractionBinding>() {

    private lateinit var player: ExoPlayer

    override fun initView(savedInstanceState: Bundle?) {
        initPlayerExo()
    }

    private fun initPlayerExo() {
        val raceId = requireArguments().getInt("raceId", 0)
        val orgId = requireArguments().getInt("orgId", 0)
        val streamUrl = Constant.LIVE_PULL_URL + raceId + "/" + orgId + "/livestream.flv"
        player = context?.let { ExoPlayer.Builder(it).build() }!!
        mDatabind.videoPlayer.player = player

        val videoUri = Uri.parse(streamUrl)
        val mediaItem = MediaItem.fromUri(videoUri)
        player.setMediaItem(mediaItem)
        player.prepare()
        player.play()

        player.addListener(object : Player.Listener {
            override fun onPlaybackStateChanged(playbackState: Int) {
                super.onPlaybackStateChanged(playbackState)
                when (playbackState) {
                    Player.STATE_BUFFERING -> LogUtils.debugInfo("加载中")
                    Player.STATE_READY -> LogUtils.debugInfo("播放中")
                    Player.STATE_ENDED -> LogUtils.debugInfo("播放完成")
                    Player.STATE_IDLE -> {}
                }
            }

            override fun onPlayerError(error: PlaybackException) {
                super.onPlayerError(error)
                showErrDialog()
                LogUtils.warnInfo(error.errorCodeName + ":" + error.errorCode)
            }
        })
    }

    private fun showErrDialog() {
        val dialog = RxDialogDefault(requireContext())
        dialog.setTitle("直播暂时未开启，请稍后重试")
        dialog.setRightBtnContent(getString(R.string.retry))
        dialog.setLeftBtnContent(getString(R.string.backing))
        dialog.setCancelListener {
            dialog.dismiss()
        }
        dialog.setSureListener {
            player.play()
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()
    }

    override fun onResume() {
        super.onResume()
        mDatabind.videoPlayer.onResume()
    }

    override fun onPause() {
        super.onPause()
        mDatabind.videoPlayer.onPause()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        player.release()
    }

    companion object {
        fun newInstance(raceId: Int, orgId: Int): FragmentLivingInteraction {
            val fragment = FragmentLivingInteraction()
            val bundle = Bundle()
            bundle.putInt("raceId", raceId)
            bundle.putInt("orgId", orgId)
            fragment.arguments = bundle
            return fragment
        }
    }
}